package edu.gmu.client;

import edu.gmu.messages.EchoResponse;
import edu.gmu.messages.EchoRequest;
import edu.gmu.middleware.ClientDispatcher;
import edu.gmu.middleware.MessageEvent;
import edu.gmu.middleware.MessageListener;
import edu.gmu.middleware.Sink;
import edu.gmu.middleware.SinkFactory;
import java.io.IOException;

public class EchoServer
{
 
    public static void main( String[] args ) throws IOException, InterruptedException
    {
        int remotePort = 5001;
        int localPort  = 5000;
        
        Sink sink = SinkFactory.makeUDPServer(remotePort, localPort);
        final ClientDispatcher dispatcher = new ClientDispatcher(sink, 7, "EchoServer");
        
        
        dispatcher.addMessageListener( new MessageListener() 
        {
            public void messageReceived(MessageEvent event)
            {
                //System.out.println( event.getMessage() );
                
                EchoRequest request = (EchoRequest)event.getMessage();
                
                EchoResponse response = new EchoResponse();
                response.count   = request.count++;
                response.missive = request.missive;
                
                try
                {
                    dispatcher.publish(1,response);
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                }
            }
        });
        dispatcher.start();
        sink.connect();
        
        dispatcher.subscribe(0, EchoRequest.class);
    }
}